﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Model.ViewModels;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;
using TomNet.Web.Mvc;
using System.IO;
using System.Drawing.Imaging;

namespace TomNet.IMSC.Web.Controllers
{
    public class UserController : BaseController
    {
        public IUsersContract UsersContract { get; set; }
        public IIntermediaryContract IntermediaryContract { get; set; }
        public IAreaContract AreaContract { get; set; }
        public IUsersLoginContract UsersLoginContract { get; set; }

        public IIntermediaryStaffContract IntermediaryStaffContract { get; set; }
        public IStaffContract StaffContract { get; set; }


        [Description("经纪人-列表")]
        //[GlobalAuthorization]
        public ActionResult Index()
        {
            return View();
        }

        [Description("经纪人-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult IndexAsync(int pageIndex, int pageSize, string search = "")
        {
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());
            //login.DepId
            var query = from m in UsersContract.Entities.Where(x => !x.IsDeleted) join b in IntermediaryContract.Entities on m.IntermediaryID equals b.Id

                        select new 
                        {
                            Id=m.Id,
                            AccountBank=m.AccountBank,
                            AccountNumber=m.AccountNumber,
                            AccountUserName=m.AccountUserName,
                            CityID=m.CityID,
                            CreatedTime=m.CreatedTime,
                            Declaration=m.Declaration,
                            IntermediaryID=m.IntermediaryID,
                            IsDeleted=m.IsDeleted,
                            IsLocked=m.IsLocked,
                            Name=m.Name,
                            OldID=m.OldID,
                            OperationPeriod=m.OperationPeriod,
                            Phone=m.Phone,
                            Portrait=m.Portrait,
                            Sex=m.Sex,
                            IntermediaryName=b.Name,
                            //房产业务员
                            HouseSalesman = (from isc in IntermediaryStaffContract.Entities.Where(o => o.IntermediaryID == b.Id && o.ModuleID == 1)
                                             join s in StaffContract.Entities.Where(e => !e.IsDeleted)
                                             on isc.StaffID equals s.Id
                                             select s.Name).FirstOrDefault(),
                            //装修业务员
                            RenovationSalesman = (from isc in IntermediaryStaffContract.Entities.Where(o => o.IntermediaryID == b.Id && o.ModuleID == 4)
                                                  join s in StaffContract.Entities.Where(e => !e.IsDeleted)
                                                  on isc.StaffID equals s.Id
                                                  select s.Name).FirstOrDefault(),
                            //金融业务员
                            FinanceSalesman = (from isc in IntermediaryStaffContract.Entities.Where(o => o.IntermediaryID == b.Id && o.ModuleID == 5)
                                               join s in StaffContract.Entities.Where(e => !e.IsDeleted)
                                               on isc.StaffID equals s.Id
                                               select s.Name).FirstOrDefault(),
                        };

            //if (login.Authority == 2)
            //{
            //    query = query.Where(x => x.DepId == login.DepId);
            //}

            //条件搜索
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.Name.Contains(search) || m.Phone.Contains(search) || m.IntermediaryName.Contains(search));
            }

            var list = (from m in query
                        select new UserShow
                        {
                            Id = m.Id,
                            Intermediary = (from m1 in IntermediaryContract.Entities where m1.Id == m.IntermediaryID select m1.Name).FirstOrDefault(),
                            Name = m.Name,
                            Phone = m.Phone,
                            Declaration = m.Declaration,
                            OperationPeriod = m.OperationPeriod,
                            AccountBank = m.AccountBank,
                            AccountUserName = m.AccountUserName,
                            AccountNumber = m.AccountNumber,
                            City = (from m2 in AreaContract.Entities where m2.Id == m.CityID select m2.Name).FirstOrDefault(),
                            CreatedTime = m.CreatedTime,
                            FinanceSalesman = m.FinanceSalesman,
                            HouseSalesman = m.HouseSalesman,
                            RenovationSalesman = m.RenovationSalesman,

                        });

            //数据总数
            var total = list.Count();

            //默认给一个排序的字段
            list = list.OrderByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            list = total > 0 ? list.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<UserShow>().AsQueryable();// null;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = list.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("经纪人-添加")]
        //[GlobalAuthorization]
        public ActionResult Insert()
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            //initDepartAndPosition(null);
            return View();
        }

        [Description("经纪人-添加")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult InsertAsync(Users entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var query = UsersContract.CheckExists(m => m.Phone.Equals(entity.Phone) && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同手机号的经纪人";
                }
                else
                {
                    //如果选择部门不为空--默认加入考勤设置-----赵兴昌
                    //if (entity.DepId != 0)
                    //{
                    //    var dep = DepContract.GetByKey(entity.DepId);
                    //    entity.AttSetId = dep.AttSetId;
                    //}
                    //if (entity.Authority == 2) entity.IsLiability = true;

                    //entity.CreateTime = DateTime.Now;

                    //事务开始
                    UsersContract.Repository.UnitOfWork.BeginTransaction();

                    var count = UsersContract.Insert(entity);
                    if (count > 0)
                    {
                        //新建经纪人登陆表
                        UsersLogin loginEntity = new UsersLogin();
                        loginEntity.LoginName = entity.Phone;
                        loginEntity.LoginPass = "123456";
                        loginEntity.LoginType = 1;
                        loginEntity.State = 1;
                        loginEntity.UserID = entity.Id;//(from m in UsersContract.Entities where m.Name == entity.Name select m.Id).FirstOrDefault();
                        loginEntity.SMSCodeID = 0;

                        var count2 = UsersLoginContract.Insert(loginEntity);

                        if(count2>0)
                        {
                            result.Type = AjaxResultType.Success;
                            result.Content = "录入成功";
                        }
                        
                        //if (entity.DepId != 0 && entity.IsLiability)
                        //{
                        //    var newuser = Contract.Entities.Where(d => d.UserName == entity.UserName).FirstOrDefault();
                        //    UpdateIsLiability(entity.DepId, newuser.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, newuser.Id);
                        //}

                        //UserInfoModel uiModel = new UserInfoModel();
                        //uiModel.Birthday = DateTime.Parse("1980-01-01");
                        //uiModel.IDNumber = "";//身份证号码
                        //uiModel.Address = "";
                        //uiModel.EMail = "";
                        //uiModel.Education = 0;
                        //uiModel.Nation = 0;//民族
                        //uiModel.PhotoId = 1;
                        //uiModel.Sex = 2;
                        //uiModel.UserId = (from m in Contract.Entities where m.UserName == entity.UserName select m.Id).FirstOrDefault();

                        //UserInfoContract.Insert(uiModel);

                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }

                    //事务结束
                    UsersContract.Repository.UnitOfWork.Commit();
                }
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("经纪人-修改")]
        //[GlobalAuthorization]
        public ActionResult Edit(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = UsersContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null)
            {
                throw new Exception("未找到该实体");
            }

            var interEntity = IntermediaryContract.GetByKey(entity.IntermediaryID);
            var cityEntity = AreaContract.GetByKey(entity.CityID);

            //initDepartAndPosition(entity);
            ViewData["entity"] = entity;
            ViewData["inter"] = interEntity==null?"":interEntity.Name;
            ViewData["city"] = cityEntity == null ? "" : cityEntity.Name;
            return View();
        }

        [Description("经纪人-修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditAsync(Users entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var query = UsersContract.CheckExists(m => m.Name.Equals(entity.Name) && m.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的经纪人";
                }
                else
                {
                    //如果选择部门不为空--默认加入考勤设置-----赵兴昌
                    //if (entity.DepId != 0)
                    //{
                    //    var dep = DepContract.GetByKey(entity.DepId);
                    //    entity.AttSetId = dep.AttSetId;
                    //}
                    //if (entity.Authority == 2) entity.IsLiability = true;

                    //获取原纪录
                    var temp = UsersContract.GetByKey(entity.Id);
                    //修改指定项
                    temp.IntermediaryID = entity.IntermediaryID;
                    temp.CityID = entity.CityID;
                    temp.Name = entity.Name;
                    temp.Phone = entity.Phone;
                    temp.Declaration = entity.Declaration;
                    temp.OperationPeriod = entity.OperationPeriod;
                    temp.AccountBank = entity.AccountBank;
                    temp.AccountUserName = entity.AccountUserName;
                    temp.AccountNumber = entity.AccountNumber;
                    
                    var count = UsersContract.Update(temp);
                    if (count > 0)
                    {
                        //if (entity.DepId != 0 && entity.IsLiability == true)
                        //{
                        //    UpdateIsLiability(entity.DepId, entity.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, entity.Id);
                        //}

                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("经纪人-查询")]
        [HttpPost, AjaxOnly]
        public ActionResult GetModelAsync(int id)
        {
            var result = new AjaxResult();

            try
            {
                var model = UsersContract.GetByKey(id);

                if (model != null)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                    result.Data = model;
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "获取失败";
                }                
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }

        [Description("经纪人-删除")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                UsersContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new Users { IsDeleted = true });
                UsersLoginContract.UpdateDirect(m => idsInt.Contains(m.UserID), m => new UsersLogin { State = 0, IsDeleted = true });
                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("经纪人-头像图片")]
        //[GlobalAuthorization]
        public ActionResult Upload(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = UsersContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null)
            {
                throw new Exception("未找到该实体");
            }

            //ViewBag.file_path = entity.LicenceImage;
            //ViewBag.file_name = Path.GetFileName(entity.LicenceImage);

            //initDepartAndPosition(entity);
            ViewData["entity"] = entity;
            return View();
        }

        [Description("经纪人-头像图片")]
        [HttpPost]
        public ActionResult UploadImageAsync()
        {
            //经纪人id
            int id = Convert.ToInt32(Request.QueryString["id"]);

            //文件流
            var oFile = Request.Files["file"];//.Files["txt_file"];
            var oStream = oFile.InputStream;
            //得到了文件的流对象，我们不管是用NPOI、GDI还是直接保存文件都不是问题了吧。。。。

            //文件名
            string m_saveName = "/images/avatar/";
            string m_savePath = Server.MapPath(m_saveName);
            string m_exName = Path.GetExtension(oFile.FileName);
            if (Directory.Exists(m_savePath) == false)
            {
                Directory.CreateDirectory(m_savePath);
            }
            string m_fileName = DateTime.Now.ToFileTime().ToString() + m_exName;

            //保存
            System.Drawing.Image img = System.Drawing.Image.FromStream(oStream);
            img.Save(m_savePath + m_fileName, ImageFormat.Jpeg);

            //// 生成临时图片-正方形的 
            //string n_file = "n_" + m_fileName;
            //ImagesHelper.imgCut(m_savePath + m_fileName, m_savePath + n_file, float.Parse(Request.Form["x"]), float.Parse(Request.Form["y"]), float.Parse(Request.Form["w"]), float.Parse(Request.Form["h"]));
            //System.IO.File.Delete(m_savePath + m_fileName);

            //string m_file = "m_" + m_fileName;
            ////-- 等比例缩放 生成新图片
            //ImagesHelper.GenerateHighThumbnail(m_savePath + n_file, m_savePath + m_file, 64, 64);
            //System.IO.File.Delete(m_savePath + n_file);

            //m_file = m_file.Replace(m_exName, "");//去掉扩展名
            //PhotoModel model = new PhotoModel()
            //{
            //    PhotoExName = oFile.FileName.Substring(oFile.FileName.LastIndexOf('.')),
            //    PhotoName = m_file,
            //    PhotoPath = m_saveName
            //};
            //PhotoContract.Insert(model);

            //var a = PhotoContract.Entities;
            //var lstOrderImport = new List<object>();
            //lstOrderImport.AddRange(PhotoContract.Entities.Where(x => x.PhotoName == m_file).ToList());
            
            //纪录图片路径
            int count = UsersContract.UpdateDirect(m => m.Id.Equals(id), m => new Users { Portrait = m_saveName + m_fileName });


            //----------------------------------
            var result = new AjaxResult();
            if (count > 0)
            {
                result.Type = AjaxResultType.Success;
                result.Content = "图片上传成功";
                //result.Data = lstOrderImport;
            }
            else
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("经纪人-头像图片")]
        //[GlobalAuthorization]
        public ActionResult View(int id)
        {
            //if (mLogin.Authority == 3)
            //{
            //    Response.Redirect("/Error/Unauthorized");
            //    return View();
            //}

            var entity = UsersContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null)
            {
                throw new Exception("未找到该实体");
            }

            //ViewBag.file_path = entity.LicenceImage;
            //ViewBag.file_name = Path.GetFileName(entity.LicenceImage);

            //initDepartAndPosition(entity);
            ViewData["imgurl"] = entity.Portrait;
            return View();
        }
        
        [Description("中介-列表")]
        //[GlobalAuthorization]
        public ActionResult IntermediaryIndex(int layerindex)
        {
            ViewData["layerindex"] = layerindex;
            return View();
        }

        [Description("中介-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult IntermediaryIndexAsync(int pageIndex, int pageSize, string Name = "", string Address="")
        {
            //LoginModel login = CookiesManagement.GetLoginModel(CookiesManagement.GetTicket());
            //login.DepId
            var query = from m in IntermediaryContract.Entities.Where(x => !x.IsDeleted) select m;

            //if (login.Authority == 2)
            //{
            //    query = query.Where(x => x.DepId == login.DepId);
            //}

            //条件搜索
            if (!string.IsNullOrWhiteSpace(Name))
            {
                query = query.Where(m => m.Name.Contains(Name));
            }
            if (!string.IsNullOrWhiteSpace(Address))
            {
                query = query.Where(m => m.Address.Contains(Address));
            }

            //var list = (from m in query
            //            select new UserShow
            //            {
            //                Id = m.Id,
            //                UserName = m.UserName,
            //                PassWord = m.PassWord,
            //                Phone = m.Phone,
            //                DepId = m.DepId,
            //                DepName = (from m1 in DepContract.Entities where m1.Id == m.DepId select m1.DepName).FirstOrDefault(),
            //                PositionName = (from m2 in PosContract.Entities where m2.Id == m.PositionId select m2.Name).FirstOrDefault(),// m.PositionId,
            //                Name = m.Name,
            //                Status = m.Status,
            //                No = m.No,
            //                IsLogin = m.IsLogin,
            //                Authority = m.Authority,
            //                IsLiability = m.IsLiability,
            //                CreatedTime = m.CreatedTime,
            //                IsDeleted = m.IsDeleted,
            //                IsLocked = m.IsLocked,
            //                AttSetName = (from n in AttSetContract.Entities where n.Id == m.AttSetId select n.Name).FirstOrDefault()
            //            });

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.CreatedTime);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : Enumerable.Empty<Intermediary>().AsQueryable();// null;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }

        [Description("城市-列表")]
        //[GlobalAuthorization]
        public ActionResult AreaIndex(int layerindex)
        {
            ViewData["layerindex"] = layerindex;
            return View();
        }

        [Description("城市-列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult AreaIndexAsync()
        {
            var data = AreaContract.Entities.Where(m => m.ParentID=="0").Select(m => new
            {
                id = m.Id,
                text = m.Name,

                children = AreaContract.Entities.Where(n => n.ParentID==m.Id).Select(n => new
                {
                    id = n.Id,
                    text = n.Name,
                    children = AreaContract.Entities.Where(t => t.ParentID==n.Id).Select(t => new
                    {
                        id = t.Id,
                        text = t.Name
                    })
                })
            }).ToList();

            return JsonEx(new
            {
                id = "0",
                text = "全部",
                children = data
            });
        }






    }
}